package org.biogroovy.io;

import groovy.util.logging.Slf4j

/**
 * This abstract class contains default methods for fetching data from
 * web-based databases and writing the data into an XML file.
 * @param <P> the POJO (model) type used by the fetcher.
 */
@Slf4j
public abstract class AbsFetcher<P> implements IFetcher<P>{
	
	/** The name of the database. */
	protected String databaseName;
	
	/**
	 * Sets the name of the database.
	 * @param name the name of the database
	 */
	public void setDatabaseName(String name){
		this.databaseName = name;
	}
	
	@Override
	public String getDatabaseName() {
		return databaseName;
	}
	
	
    /**
     * This method creates a default file name based on the ID.
     * @param id the ID of the object being fetched.
     * @return a file object
     */
    public File createDefaultFile(String id){
        return new File("${System.getProperty('user.home')}", createFileName(id));
    }

    /**
     * This method creates a default file.
     * @param outputDir the output directory for the file
     * @param id the id of the object being fetched.
     * @return a file object
     */
    public File createDefaultFile(File outputDir, String id){
        return new File(outputDir, createFileName(id))
    }

    /**
     * This method creates a file name.
     * @param id the id of the object being fetched
     * @return a filename.
     */
    public String createFileName(String id){
        return "/${id}.${getDatabaseName()}.xml"
    }

    @Override
    public void fetchAsFile(String id, File outFile) throws IOException {
        URL url = getUrl(id, null);
        if(outFile == null){
            outFile = createDefaultFile(id)
        }
        FileOutputStream fos = new FileOutputStream(outFile)
        BufferedOutputStream out = new BufferedOutputStream(fos)
        out << url.openStream()
		out.flush()
        out.close()
    }



    @Override
    public void fetchAsFiles(File outDir, String idList) throws IOException {
        String[] ids = idList.split(",")

        if (outDir == null){
            outDir = new File("${System.getProperty('user.home')}")
        }
        ids.each{String id ->
            URL url = getUrl(id, new HashMap<String, String>())
            File outFile = new File(outDir, createFileName(id))
			log.info("Downloading: ${id}")
            FileOutputStream fos = new FileOutputStream(outFile)
            BufferedOutputStream out = new BufferedOutputStream(fos)
            out << url.openStream()
			out.flush()
            out.close()
			log.info("Finished download: ${id}")
        }
    }
}
